package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class GetReferenceAndDetachedEntityExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEntity(emf);
        Employee employee = getEntityReference(emf);
        EntityManager em = emf.createEntityManager();
        employee = em.merge(employee);
        System.err.println(JSONObject.toJSONString(employee,true));
        em.close();
    }
    private static Employee getEntityReference(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.getReference(Employee.class,1);
        em.close();
        return employee;
    }
    private static Employee persistEntity(EntityManagerFactory emf){
        System.err.println("--- persisting employee ---");
        Employee employee = new Employee("Sara Dorsey","Admin");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        em.close();
        return employee;
    }
}
